//标识：区分当前是新增还是修改
let editId = ''
// 1.登录鉴权
checkLogin()
// 2.渲染用户名
renderUserName()
// 3.绑定退出事件
logout()

// 4.获取学生列表数据
getStudentData()
async function getStudentData() {
    const { data } = await axios({ url: '/students' })
    console.log(data);
    const htmlStr = data.map(item => {
        return `<tr>
                      <td>${item.name}</td>
                      <td>${item.age}</td>
                      <td>${item.gender === 0 ? '男' : '女'}</td>
                      <td>第${item.group}组</td>
                      <td>${item.hope_salary}</td>
                      <td>${item.salary}</td>
                      <td>${item.province}${item.city}${item.area}</td>
                      <td data-id=${item.id}>
                        <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
                        <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
                      </td>
                    </tr>`
    }).join('')
    document.querySelector('.list').innerHTML = htmlStr
    document.querySelector('.total').innerText = data.length
}
// 初始化一个添加的模态框
const addModel = new bootstrap.Modal(document.querySelector('#modal'))
// 5.新增学生数据
addStudentData()
function addStudentData() {

    // 1.给添加按钮绑定点击事件，展示添加的模态框
    document.querySelector('#openModal').addEventListener('click', async function (e) {
        e.preventDefault()
        editId = ''
        // 表单标题修改
        document.querySelector('#modal .modal-title').innerText = '新增学员'
        // 表单清空
        document.querySelector('form').reset()
        // 获取省市区的数据
        await getAddressList()
        // 打开模态框
        addModel.show()
    })
}
// 获取和渲染省份
async function getProvinceData() {
    // 省份
    const { list: provinceList } = await axios({ url: '/api/province' })

    const provinceHtml = provinceList.map(province => {
        return ` <option value="${province}">${province}</option>`
    }).join('')
    document.querySelector('[name=province]').innerHTML = provinceHtml
}
// 获取和渲染城市
async function getCityData() {
    // 城市
    const { list: cityList } = await axios({
        url: '/api/city',
        params: {
            pname: document.querySelector('[name=province]').value
        }
    })

    const cityHtml = cityList.map(city => {
        return ` <option value="${city}">${city}</option>`
    }).join('')
    document.querySelector('[name=city]').innerHTML = cityHtml
}
// 获取和渲染地区
async function getAreaData() {
    // 地区
    const { list: areaList } = await axios({
        url: '/api/area',
        params: {
            pname: document.querySelector('[name=province]').value,
            cname: document.querySelector('[name=city]').value
        }
    })

    const areaHtml = areaList.map(area => {
        return ` <option value="${area}">${area}</option>`
    }).join('')
    document.querySelector('[name=area]').innerHTML = areaHtml
}
// 渲染省市区列表及绑定事件
async function getAddressList() {
    // 获取省市区
    await getProvinceData()
    await getCityData()
    await getAreaData()
    // 省份切换绑定事件
    document.querySelector('[name=province]').addEventListener('change', async function () {
        await getCityData()
        await getAreaData()
    })
    // 城市切换绑定事件
    document.querySelector('[name=city]').addEventListener('change', async function () {
        getAreaData()
    })
}

// 绑定模态框的点击确定事件
document.querySelector('#submit').addEventListener('click', async function (e) {
    e.preventDefault()
    // 收集表单数据
    const form = document.querySelector('form')
    const formData = serialize(form, { hash: true, empty: true })
    // 校验表单数据
    // 后台提交
    if (editId === '') {
        await axios({
            url: '/students',
            method: 'POST',
            data: {
                ...formData,
                age: Number(formData.age),
                gender: Number(formData.gender),
                hope_salary: Number(formData.hope_salary),
                salary: Number(formData.salary),
                group: Number(formData.group),
            }
        })

    } else {
        await axios({
            url: '/students/' + editId,
            method: 'PUT',
            data: {
                ...formData,
                age: Number(formData.age),
                gender: Number(formData.gender),
                hope_salary: Number(formData.hope_salary),
                salary: Number(formData.salary),
                group: Number(formData.group),
            }
        })
    }

    // 提示用户
    showToast(editId === '' ? '新增成功' : '修改成功')
    // 刷新列表
    getStudentData()
    // 关闭模态框
    addModel.hide()
})

// 删除和编辑学生数据
document.querySelector('.list').addEventListener('click', async function (e) {
    if (e.target.classList.contains('bi-pen')) {
        // 记录当前编辑的id
        editId = e.target.parentNode.parentNode.dataset.id
        document.querySelector('#modal .modal-title').innerText = '修改学员'
        // 获取学生详细信息回填
        const { data } = await axios({
            url: `/students/${e.target.parentNode.parentNode.dataset.id}`
        })
        getAddressList()
        await getProvinceData()
        const pOptions = document.querySelectorAll('[name=province] option')
        pOptions.forEach(item => {
            if (item.innerText === data.province) {
                item.selected = true
            }
        })
        await getCityData()
        const cOptions = document.querySelectorAll('[name=city] option')
        cOptions.forEach(item => {
            if (item.innerText === data.province) {
                item.selected = true
            }
        })
        await getAreaData()
        const aOptions = document.querySelectorAll('[name=area] option')
        aOptions.forEach(item => {
            if (item.innerText === data.province) {
                item.selected = true
            }
        })
        // 回填数据
        document.querySelector('[name=name]').value = data.name
        document.querySelector('#cb01').checked = data.gender === 0
        document.querySelector('#cb02').checked = data.gender === 1
        document.querySelector('[name=age]').value = data.age
        document.querySelector('[name=group]').value = data.group
        document.querySelector('[name=hope_salary]').value = data.hope_salary
        document.querySelector('[name=salary]').value = data.salary
        // 下拉框必须有选项才能设置值


        addModel.show()

    } else if (e.target.classList.contains('bi-trash')) {
        console.dir(e.target);

        if (confirm('确认删除吗？')) {
            await axios({
                url: `/students/${e.target.parentNode.parentNode.dataset.id}`,
                method: 'DELETE'
            })
            showToast('删除成功')
            getStudentData()
        }
    }
})

